package com.tfswue.mxj.config;



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启websecurity配置
@EnableWebSecurity
public class SecurityConfig {
    //配置密码加密器（必需）
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(); //使用BCrypt强哈希加密
    }
    //配置用户存储（内存方式，生产环境需连接数据库）
    @Bean
    public UserDetailsService userDetailsService(){
        //创建两个测试用户
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass"))
                .roles("USER")//分配角色
                .build();
        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN","USER")//可分配多个角色
                .build();
        return new InMemoryUserDetailsManager(user,admin);//存储在内存中
    }
    //核心安全配置（HTTP 请求过滤规则）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/","index").permitAll() //允许根路径匿名访问
                        .requestMatchers("/public/**").permitAll() //公共路径无需认证
                        .requestMatchers("/admin/**").hasRole("ADMIN") //仅管理员可访问
                        .anyRequest().authenticated() //其他所有请求需认证
                )
                .formLogin(form -> form
                        .loginPage("/index.html") //与实际文件路径一致
                        .loginProcessingUrl("/login") //处理登录的URL
                        .defaultSuccessUrl("/public/hello") //登录成功后固定跳转到此处
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/public/goodbye") //登出后跳转地址
                        .permitAll()
                )
                //.csrf().disable(); //禁用CSRF保护（开发环境方便测试）
                .csrf(csrf -> csrf.disable());
        return http.build();
    }
}